package com.goomba.order;

import com.goomba.demo.contants.Commons;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

/**
 * 如果我们需要全局有效，那么我们最好的办法就是只指定一个队列，这样一般情况下无意义。我们只需要将我们具体的某一类放入队列，保证局部有序最好
 * 选择性的发送信息到指定的队列, 比如我们存在N个队列。我们用数据中的属性S的Hash mod N = x, x就是我们指定放入的队列。
 */
public class SyncOrderProducer {


    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("group_order");
        producer.setNamesrvAddr(Commons.nameSrvAddr);
        producer.setSendMsgTimeout(1500);

        List<Order> lists = builderDefaultOrder();
        producer.start();

        for (Order order : lists) {
            Message message = new Message("sync_order_topic", "tag1", (order.id + ":" + order.name + ":" + order.desc).getBytes(StandardCharsets.UTF_8));

            // MessageQueueSelector
            producer.send(message, (list, message1, id) -> {
                System.out.println("list size is " + list.size());
                long orderId = (long) id;
                int index = Math.toIntExact(orderId % list.size());
                return list.get(index);
            }, order.id);

        }


        producer.shutdown();


    }


    private static List<Order> builderDefaultOrder() {

        List<Order> results = new LinkedList<>();

        Order order = new Order(100L, "郑义", "开始");
        Order order2 = new Order(100L, "郑义", "进行001");
        Order order3 = new Order(100L, "郑义", "进行002");
        Order order4 = new Order(100L, "郑义", "结束");

        Order order5 = new Order(101L, "张三", "开始");
        Order order6 = new Order(101L, "张三", "进行中....");
        Order order7 = new Order(101L, "张三", "结束");

        results.add(order);
        results.add(order2);
        results.add(order3);
        results.add(order4);
        results.add(order5);
        results.add(order6);
        results.add(order7);

        return results;


    }


    // 订单类
    static class Order {
        private long id;
        private String name;
        private String desc;

        public Order(long id, String name, String desc) {
            this.id = id;
            this.name = name;
            this.desc = desc;
        }
    }


}
